<template>
    <div class="wrapper">
        <t-card class="margin-bottom">
            <span class="card-content">
                Hi,{{ name }} {{ greeting }}，今天是你加入我们的第{{ createTime }}天，感谢你的加入，希望你在这里能够收获满满。
            </span>
        </t-card>
        <t-card>
            <template #header>
                <div class="header-wrapper">
                    <h2 class="card-title">个人资料</h2>
                    <t-button theme="primary" variant="text" @click="openChangePassword" size="medium">
                        修改密码
                    </t-button>
                </div>
            </template>
            <t-space direction="vertical" size="large">
                <t-form ref="form" :data="formData" :rules="updateRules">
                    <t-form-item label="邮箱" name="email">
                        <t-input v-model="formData.email" disabled />
                    </t-form-item>
                    <t-form-item label="姓名" name="name">
                        <t-input v-model="formData.name" placeholder="请输入姓名" />
                    </t-form-item>
                    <t-form-item label="手机号" name="phone">
                        <t-input v-model="formData.phone" placeholder="请输入手机号" />
                    </t-form-item>
                    <t-form-item label="性别" name="gender">
                        <t-radio-group v-model="formData.gender">
                            <t-radio value="男">男</t-radio>
                            <t-radio value="女">女</t-radio>
                        </t-radio-group>
                    </t-form-item>
                    <t-form-item label="生日" name="birthday">
                        <t-date-picker v-model="formData.birthday" mode="date" />
                    </t-form-item>
                    <t-form-item label="地址" name="address">
                        <t-textarea v-model="formData.address" placeholder="请输入地址" />
                    </t-form-item>
                </t-form>

                <t-space>
                    <t-button theme="primary" @click="onSubmit">保存</t-button>
                    <t-button theme="default" @click="onReset">重置</t-button>
                </t-space>
            </t-space>
        </t-card>
    </div>

    <t-dialog :visible="showPasswordDialog" header="修改密码" :footer="false" width="500px" @close="onCloseDialog">
        <t-form ref="passwordForm" :data="passwordData" :rules="passwordRules">
            <t-form-item style="display: none;">
                <t-input :value="formData.email" type="text" autocomplete="email" />
            </t-form-item>
            <t-form-item label="当前密码" name="oldPassword">
                <t-input v-model="passwordData.oldPassword" type="password" placeholder="请输入当前密码"
                    :autocomplete="'current-password'" />
            </t-form-item>
            <t-form-item label="新密码" name="newPassword">
                <t-input v-model="passwordData.newPassword" type="password" placeholder="请输入新密码"
                    :autocomplete="'new-password'" />
            </t-form-item>
            <t-form-item label="确认新密码" name="confirmPassword">
                <t-input v-model="passwordData.confirmPassword" type="password" placeholder="请再次输入新密码"
                    :autocomplete="'new-password'" />
            </t-form-item>
            <t-form-item>
                <t-button theme="primary" @click="onChangePassword" block>确认</t-button>
            </t-form-item>
        </t-form>
    </t-dialog>

    <t-dialog header="确认重置" :visible="showResetDialog" :on-confirm="handleReset"
        :on-close="() => showResetDialog = false">
        <template #body>
            <p>重置将丢失未保存的修改，是否继续？</p>
        </template>
    </t-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { getUserProfile, changePassword, editUserProfile } from '@/api/login'

import { useUserStore } from '@/store'
import { UserInfoList } from '@/types/interface'
import type { FormInstanceFunctions } from 'tdesign-vue-next';


const userStore = useUserStore()
const id = userStore.id
const name = userStore.name
const greeting = computed(() => {
    const hour = new Date().getHours()
    if (hour < 6) return '凌晨好'
    if (hour < 9) return '早上好'
    if (hour < 12) return '上午好'
    if (hour < 14) return '中午好'
    if (hour < 18) return '下午好'
    if (hour < 24) return '晚上好'
    return '你好'
})
const createTime = ref<string>('')

// 获取用户信息
const fetchUserProfile = async () => {
    try {
        const params = {
            id: id
        }
        const res = await getUserProfile(params)

        if (res.errcode == 0) {
            formData.value = res.data.profile
            createTime.value = res.data.create_time
        }
    } catch (error) {
        MessagePlugin.error('获取用户信息失败')
    }
}

const form = ref<FormInstanceFunctions>()
const formData = ref<UserInfoList>({
    id: 0,
    email: '',
    name: '',
    phone: '',
    gender: '',
    birthday: '',
    address: '',
    update_time: ''
})
const updateRules = ref({
    phone: [
        {
            validator: (val: string) => {
                if (val && !/^1[3-9]\d{9}$/.test(val)) {
                    return { result: false, message: '请输入正确的11位手机号码' };
                }
                return { result: true };
            },
        },
    ],
});

const showResetDialog = ref(false)
const onReset = () => {
    showResetDialog.value = true
}

const handleReset = () => {
    fetchUserProfile()
    showResetDialog.value = false
}
const onSubmit = async () => {
    const validateResult = await form.value?.validate();
    if (!validateResult) return;

    try {
        const params = {
            id: formData.value.id,
            email: formData.value.email,
            name: formData.value.name,
            phone: formData.value.phone,
            gender: formData.value.gender,
            birthday: formData.value.birthday,
            address: formData.value.address,
            uid: id,
        }
        const res = await editUserProfile(params);
        if (res.errcode == 0) {
            MessagePlugin.success(res.message, 1000);
            fetchUserProfile()
        }
    } catch (error) {
        MessagePlugin.error('保存失败')
    }
}

const passwordForm = ref<FormInstanceFunctions>()
const passwordData = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

const passwordRules = {
    oldPassword: [{ required: true, message: '请输入当前密码', type: 'error' }],
    newPassword: [
        { required: true, message: '请输入新密码', type: 'error' },
        { min: 6, message: '密码长度至少6位', type: 'error' }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入新密码', type: 'error' },
        {
            validator: (val: string) => val === passwordData.value.newPassword,
            message: '两次输入的密码不一致',
            type: 'error'
        }
    ]
}

const showPasswordDialog = ref(false)
const openChangePassword = () => {
    passwordForm.value?.reset()
    showPasswordDialog.value = true
}

const onChangePassword = async () => {
    const valid = await passwordForm.value?.validate()
    if (!valid) return

    try {
        const params = {
            id: id,
            old_password: passwordData.value.oldPassword,
            new_password: passwordData.value.newPassword,
            uid: id,
        }
        const res = await changePassword(params)

        if (res.errcode == 0) {
            MessagePlugin.success('密码修改成功')
            onCloseDialog()
        }
    } catch (error) {
        console.error('密码修改失败', error);
        // MessagePlugin.error('密码修改失败')
    }
}

// 关闭弹窗
const onCloseDialog = () => {
    showPasswordDialog.value = false
}

onMounted(() => {
    fetchUserProfile()
})
</script>

<style scoped>
.wrapper {
    padding: 20px;
}

.margin-bottom {
    margin-bottom: 12px;
}

.card-content {
    font-size: 16px;
    color: #666;
    font-weight: normal;
}

.card-title {
    font-size: 20px;
    font-weight: 500;
    color: #0d0d0d;
    margin: 0;
}

:deep(.t-card__header) {
    padding-bottom: 24px;
    border-bottom: 1px solid #e7e7e7;
}

:deep(.t-card__body) {
    padding: 32px 24px;
}


:deep(.t-form) {
    max-width: 560px;
    margin: 0 auto;
}

:deep(.t-space) {
    justify-content: center;
}

.password-card {
    max-width: 680px;
    margin: 24px auto 0;
}

.header-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.dialog-footer {
    margin-top: 24px;
    text-align: right;
}

:deep(.t-dialog__body) {
    padding: 24px;
}

:deep(.t-dialog .t-form) {
    margin: 0;
}
</style>
